import os
from time import sleep
import time
from flask import Flask, request, jsonify
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.keys import Keys
from threading import Lock

app = Flask(__name__)

start_url = "https://open.alipay.com/api/diagnosticTool?expand=DI00001054&subCode=DI00001227"

# 谷歌浏览器选项
chrome_options = Options()
chrome_options.add_argument("--disable-gpu")
# chrome_options.add_argument("--headless")  # 非调试模式下使用无头模式

chrome_driver_path = 'chromedriver.exe' 
# 初始化WebDriver
service = Service(executable_path=chrome_driver_path)
driver = None
wait = None

# 初始化浏览器的标志
is_browser_initialized = False

# 创建一个线程锁
lock = Lock()

def initialize_browser():
    global driver, wait, is_browser_initialized
    if not is_browser_initialized:
        driver = webdriver.Chrome(service=service, options=chrome_options)
        driver.get(start_url)
        wait = WebDriverWait(driver, 10)  # 增加等待时间以确保页面加载完成

        # 等待页面加载完成
        wait.until(EC.presence_of_element_located((By.TAG_NAME, 'body')))

        # 查找登录元素
        login_element_selector = 'div.alipay-open-common-login'
        login_element = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, login_element_selector)))

        # 如果登录元素存在，点击该元素
        if login_element:
            login_element.click()
            print("点击登录按钮")

        # 等待用户扫码
        while True:
            try:
                login_element = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, login_element_selector)))
                print("等待用户登录...")
                sleep(1)
            except TimeoutException:
                print("用户登录成功...")
                break

        is_browser_initialized = True

@app.route('/diagnose', methods=['GET'])
def diagnose():
    trade_no = request.args.get('trade_no')
    if not trade_no:
        return jsonify({'error': 'trade_no is required'}), 400

    # 获取锁
    with lock:
        # 初始化浏览器
        initialize_browser()

                # # 切换到 iframe
        iframe_selector = 'iframe[src="https://opensupport.alipay.com/support/instrument/dd59ab8e-5de5-419e-8b40-0469d25addc4"]'
        iframe = wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, iframe_selector)))

        # 输入 trade_no
        input_selector = 'input[placeholder="请输入out_trade_no/trade_no"]'
        input_element = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, input_selector)))
        input_element.clear()  # 清除输入框内容
        input_element.send_keys(Keys.CONTROL, 'a')
        time.sleep(0.1)
        input_element.send_keys(Keys.BACKSPACE)
        
        
        input_element.send_keys(trade_no)
        print("输入 trade_no 成功")

        # 点击“开始诊断”按钮
        button_selector = 'button.ant-btn.css-1x0dypw.ant-btn-primary.ant-btn-color-primary.ant-btn-variant-solid'
        button_element = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, button_selector)))
        button_element.click()
        print("点击“开始诊断”按钮成功")
        js = 'var ifm =document.querySelector("src[https://opensupport.alipay.com/support/instrument/dd59ab8e-5de5-419e-8b40-0469d25addc4]");ifm.querySelector("input[placeholder=\'请输入out_trade_no/trade_no\']").value = "";'
        js = """
        var ifm = document.querySelector('iframe[src="https://opensupport.alipay.com/support/instrument/dd59ab8e-5de5-419e-8b40-0469d25addc4"]');
        if (ifm) {
            ifm.contentWindow.document.querySelector('input[placeholder="请输入out_trade_no/trade_no"]').value = "";
        }
        """
        # js = 'document.querySelector("input[placeholder=\'请输入out_trade_no/trade_no\']").value = "";'
        driver.execute_script(js)
        print("清空输入框")
        try:

         # 查找表格中的所有行
            rows = wait.until(EC.presence_of_all_elements_located((By.XPATH, '//*[@id="root"]/div/div[4]/div[2]/div/div/div[2]/div[2]/div/div/table/tbody/tr')))
            
            # 提取所有字段
            data = []
            for row in rows:
                cells = row.find_elements(By.TAG_NAME, 'td')
                if len(cells) == 8:
                    data.append({
                        '支付宝交易号': cells[0].text,
                        '外部订单号': cells[1].text,
                        '收单产品': cells[2].text,
                        '交易状态': cells[3].text,
                        '付款方id/付款方状态': cells[4].text,
                        '收款方id/收款方状态': cells[5].text,
                        '金额': cells[6].text,
                        '时间': cells[7].text
                    })
            
            print("提取的内容:", data)
            return jsonify({'code': 200, 'msg': '查询成功', 'data': {'trade_no': trade_no, 'diagnose_data': data}})
            # return jsonify({'trade_no': trade_no, 'data': data})
        except TimeoutException:
            print("在指定时间内未找到目标元素，可能需要检查网页链接的合法性或网络连接。")
            return jsonify({'code': 404, 'msg': '目标元素未找到', 'data': None}), 404        

        
        finally:
            # 切换回主文档
            driver.switch_to.default_content()

if __name__ == '__main__':
    app.run(debug=True, port=5000)